package org.csc.sss.util.api;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ReflectUtils {

    public static void handleModel(Object model) {
        List<Field> fieldList = new ArrayList<>() ;
        Class tempClass = model.getClass();
        while (tempClass != null) { // 当父类为null的时候说明到达了最上层的父类(Object类).
            fieldList.addAll(Arrays.asList(tempClass .getDeclaredFields()));
            tempClass = tempClass.getSuperclass(); // 得到父类,然后赋给自己
        }

        try {
            for (int j = 0; j < fieldList.size(); j++) { // 遍历所有属性
                String name = fieldList.get(j).getName(); // 获取属性的名字
                String uppercaseName = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写，方便构造get，set方法
                String type = fieldList.get(j).getGenericType().toString(); // 获取属性的类型
                if (type.equals("class java.lang.Integer")) {
                    Method m = model.getClass().getMethod("get" + uppercaseName);
                    if (null == m) { // get方法不存在
                        continue;
                    }
                    Integer value = (Integer) m.invoke(model); // 值
                    if (null == value) {
                        continue;
                    }
                    if (name.equals("gender") &&  checkModel(fieldList, name + "Str")) {
                        m = model.getClass().getMethod("set" + uppercaseName + "Str", String.class);
                        m.invoke(model, "");
                    }
                    if (name.equals("type") &&  checkModel(fieldList, name + "Str")) {
                        m = model.getClass().getMethod("set" + uppercaseName + "Str", String.class);
                        m.invoke(model, "");
                    }
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private static boolean checkModel(List<Field> fieldList, String modelName) {
        for (int j = 0; j < fieldList.size(); j++) {
            String type = fieldList.get(j).getGenericType().toString(); // 获取属性的类型
            if (fieldList.get(j).getName().equals(modelName) && type.equals("class java.lang.String")) {
                return true;
            }
        }
        return false;
    }
}